<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        span {
            position: absolute;
            width: 150px;
            height: 150px;
            display: block;
            background-color: purple;
            margin-top: 200px;
        }
    </style>
</head>
<body>
    <button class="btn500">500</button>
    <button class="btn800">800</button>
    <span></span>
    <script>
        function animate(obj,target,callback){
            clearInterval(obj.timer);
            obj.timer = setInterval(function(){
            var step =(target - obj.offsetLeft )/10;
            step = step > 0? Math.ceil(step):Math.floor(step);
            if(obj.offsetLeft == target){
                //清楚定时器
                clearInterval(obj.timer);
                if (callback) {
                    callback();
                }
            }else {
                obj.style.left = obj.offsetLeft + step +'px';
            }
        },50)
        }
        var span = document.querySelector('span');
        var btn = document.querySelector('.btn500');
        var btn1 = document.querySelector('.btn800');
        btn.addEventListener('click',function(){
            animate(span,500,function(){
                span.style.backgroundColor = 'green';
            });
        })
        btn1.addEventListener('click',function(){
            animate(span,1000,function(){
                span.style.backgroundColor = 'red';
            });
        })

    </script>
</body>
</html>